package com.lwm.demo.dao.impl;

import com.lwm.demo.dao.IAccountDAO;
import com.lwm.demo.pojo.AccountDO;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author liweimin
 * @date 2021/6/9 19:17
 * @since
 */
@Repository
public class AccountDAOImpl implements IAccountDAO {
    @Autowired
    private QueryRunner queryRunner;


    @Override
    public List<AccountDO> findAll() {
        try {
            return queryRunner.query("select * from account", new BeanListHandler<AccountDO>(AccountDO.class));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public AccountDO findAccountById(Integer id) {
        try {
            return queryRunner.query("select * from account where id = ?", new BeanHandler<AccountDO>(AccountDO.class), id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }



    @Override
    public int saveAccount(AccountDO accountDO) {
        try {
            return queryRunner.update("insert into  account(name,money) values(? ?)", accountDO.getName(), accountDO.getMoney());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int deleteAccount(Integer id) {
        try {
            return queryRunner.update("delete from account where id = ?", id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateAccount(AccountDO accountDO) {
        try {
            return queryRunner.update("update  account set name = ? ,money = ? where id = ?", accountDO.getName(), accountDO.getMoney(), accountDO.getId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
